package com.simpleim.starter.handler;

import com.simpleim.common.ProtoInstant;
import com.simpleim.im.common.bean.msg.ProtoMsg;
import com.simpleim.starter.client.ClientSession;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class LoginResponseHandler extends SimpleChannelInboundHandler<ProtoMsg.Message> {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginResponseHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ProtoMsg.Message msg) throws Exception {
        ProtoMsg.HeadType headType = msg.getType();
        if (!(headType == ProtoMsg.HeadType.LOGIN_RESPONSE)) {
            ctx.fireChannelRead(msg);
            return;
        }

        ProtoMsg.LoginResponse response = msg.getLoginResponse();
        if (response.getCode() == ProtoInstant.ResultCodeEnum.SUCCESS.getCode()) {
            // 添加心跳过滤器
            final Channel channel = ctx.channel();
            channel.pipeline().addAfter("login", "heartbeat", new HeartBeatClientHandler());
            channel.pipeline().addAfter("login", "chatMsg", new ChatMsgHandler());
            channel.pipeline().remove(this);
            ClientSession.loginSuccess(ctx, msg);
        } else {
            // 登录失败
            LOGGER.info(response.getInfo());
        }
    }
}
